<?php
/**
 * XMLDB resourcepage module update script
 *
 * @copyright &copy; 2007 The Open University
 * @author D.A.Woolhead@open.ac.uk
 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
 * @package resourcepage
 */

// This file keeps track of upgrades to 
// the resourcepage module
//
// Sometimes, changes between versions involve
// alterations to database structures and other
// major things that may break installations.
//
// The upgrade function in this file will attempt
// to perform all the necessary actions to upgrade
// your older installtion to the current version.
//
// If there's something it cannot do itself, it
// will tell you what you need to do.
//
// The commands in here will all be database-neutral,
// using the functions defined in lib/ddllib.php

function xmldb_resourcepage_upgrade($oldversion=0) {

    global $CFG, $THEME, $db;

    $result = true;

/// And upgrade begins here. For each one, you'll need one 
/// block of code similar to the next one. Please, delete 
/// this comment lines once this file start handling proper
/// upgrade code.

/// if ($result && $oldversion < YYYYMMDD00) { //New version in version.php
///     $result = result of "/lib/ddllib.php" function calls
/// }

    if ($result && $oldversion < '2007022800') { 

        // Rename old resourcepage_placeholderitems table if it exists
        // Note: XMLDB equivalent of old resourcepage_upgrade stuff now removed
        if (table_exists($t_rpphi = new XMLDBTable('resourcepage_placeholderitems'))) {
            // Prevent error due to table without id/sequence column
            //$result = rename_table($t_rpphi, 'resourcepage_placeholderitms');
            $result = execute_sql('ALTER TABLE '.$CFG->prefix.'resourcepage_placeholderitems'.
                                  ' RENAME TO '.$CFG->prefix.'resourcepage_placeholderitms');
        }

        // Check if the resourcepage_canned table has an id column
        $tableorig = 'resourcepage_canned';
        $tablexml = 'install_canned.xml';

        $table = new XMLDBTable($tableorig);
        $field = new XMLDBField('id');
        // Check table field exists
        if (!field_exists($table, $field)) {
            $result = false;
            // Table field does not exist, check for table create xml file
            if (file_exists(dirname(__FILE__).'/'.$tablexml)) {
                $tw=new transaction_wrapper();
                // Rename existing table and re-install new table
                // Prevent error due to table without id/sequence column
                //$result = rename_table($table, $tableorig.'temp');
                if (execute_sql('ALTER TABLE '.$CFG->prefix.$tableorig.
                                ' RENAME TO '.$CFG->prefix.$tableorig.'temp') &&
                    install_from_xmldb_file(dirname(__FILE__).'/'.$tablexml)) {

                    // Copy data from existing table to new table
                    // Note: Cannot use get_records as first col is not unique
                    $rs = get_recordset($tableorig.'temp');
                    if ($rs && $rs->RecordCount() > 0) {
                        $ok = true;
                        while ($ok && !$rs->EOF) {
                            $recobj = $rs->FetchObj();
                            $ok = insert_record($tableorig, addslashes_object($recobj), false);
                            $rs->MoveNext();
                        }
                        // Check both tables now have the same number of records
                        if ($ok && (count_records($tableorig) == count_records($tableorig.'temp'))) {
                            // Drop old existing table
                            // Prevent error due to possible foreign key constraint
                            //$result = drop_table(new XMLDBTable($tableorig.'temp'));
                            $result = execute_sql('DROP TABLE '.$CFG->prefix.$tableorig.'temp'.' CASCADE');
                        }
                    }
                }
                $tw->complete($result);
            }
        }

    }
    
    if ($result && $oldversion < '2007090401') {
        
        $tw=new transaction_wrapper();
        $baditems=get_records_select('resourcepage_items','itemtype IS NULL AND basedonitemid IS NULL','','id');
        if($baditems) {
            foreach($baditems as $baditem) {
                module_resourcepage::$inst->delete_item($baditem->id);
            }
        }
        
        if($CFG->dbtype=='postgres7') {
            // For Postgres, add a check constraint that prevents illegal rows of a type we've seen
            $result=execute_sql('ALTER TABLE '.$CFG->prefix.'resourcepage_items ADD CONSTRAINT '.
                $CFG->prefix.'resourcepage_itemtype_ck CHECK(basedonitemid IS NOT NULL OR itemtype IS NOT NULL)');
        }
        $tw->complete($result);
        
    }

    if ($result && $oldversion < '2007090600') {

        if($CFG->dbtype=='postgres7') {
            // For Postgres (existing installation), allow weblinks >= 256 chars (up to 511)
            $result .= execute_sql('ALTER TABLE '.$CFG->prefix.'resourcepage_items ALTER COLUMN weblink TYPE VARCHAR(511)');
        }
    }

    if ($result && $oldversion < 2007092500) {
        // Define field rights to be added to resourcepage_items. Note
        // because this initially had an older version number, it was not
        // run, so this code has been refactored to check whether it already
        // exists. Same check applies to entire update not just the field.
        $table = new XMLDBTable('resourcepage_items');
        $field = new XMLDBField('rights');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, null, null, null, null, null, 'options');
        if(!field_exists($table,$field)) {        
            $tw=new transaction_wrapper();
    
            // Launch add field rights
            $result = $result && add_field($table, $field);
    
            // Place attachment details from the post table into the attachments table
            $result = $result && execute_sql("UPDATE ".$CFG->prefix."resourcepage_items SET rights = 1 WHERE itemtype = 'file'" );
        
            if($result) {
                $tw->commit();
            }
        }
    }
    
    if ($result && $oldversion < 2008022001) {
        
        /// Define field publicfeed to be added to resourcepage
            $table = new XMLDBTable('resourcepage');
            $field = new XMLDBField('publicfeed');
            $field->setAttributes(XMLDB_TYPE_INTEGER, '5', null, null, null, null, null, null, 'shared');

        if(!field_exists($table,$field)) {        
            $tw=new transaction_wrapper();
    
            /// Launch add field publicfeed
                $result = $result && add_field($table, $field);
                
           if($result) {
                $tw->commit();
            }
            
            
        } // endif
        
        
    } // endif

    if ($result && $oldversion < 2008072103) {

    /// Define field allmailings to be added to resourcepage_x_etexts
        $table = new XMLDBTable('resourcepage_x_etexts');
        $field = new XMLDBField('allmailings');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'coursepres');

    /// Launch add field allmailings
        $result = $result && add_field($table, $field);
        
    /// Reset field value
        $result = $result && set_field('resourcepage_x_etexts','allmailings',1,'','');
    }
    

   if ($result && $oldversion < 2008091800) {

    /// Define field livedate to be added to resourcepage_containers
        $table = new XMLDBTable('resourcepage_containers');
        $field1 = new XMLDBField('livedate');
        $field1->setAttributes(XMLDB_TYPE_INTEGER, '8', XMLDB_UNSIGNED, null, null, null, null, null, 'resourcepageid');
    /// Define field removedate to be added to resourcepage_containers
        $field2 = new XMLDBField('removedate');
        $field2->setAttributes(XMLDB_TYPE_INTEGER, '8', XMLDB_UNSIGNED, null, null, null, null, null, 'livedate');
	/// Define field showto
        $field3 = new XMLDBField('showto');
        $field3->setAttributes(XMLDB_TYPE_CHAR, '255', XMLDB_UNSIGNED, null, null, null, null, null, 'removedate');
        
    /// Launch add fields livedate, removedate, showto
        if(!field_exists($table,$field1)) {        
            $tw=new transaction_wrapper();
        
        	$result = $result && add_field($table, $field1);
        	
        	if($result) {
        		$result = $result && add_field($table, $field2);
        	}
        	if($result) {
        		$result = $result && add_field($table, $field3);
        	}
        	
        	if($result) {
                $tw->commit();
            }
            
        } // endif fields do not exist
        	        
    } // endif
    
    
   // use weblink to hold forumlink details so that descriptions can be added to forumlinks
   if ($result && $oldversion < 2008100100) {
    
    // update muddle_resourcepage_items set weblink = description, description = '' where itemtype = 'forumlink'
    
		$tw=new transaction_wrapper();
    
           // update resourcepage_items for forumlinks 
           $result = execute_sql("UPDATE ".$CFG->prefix."resourcepage_items SET weblink = description, description = '' WHERE itemtype = 'forumlink'");
        
            if($result) {
                $tw->commit();
            }
   	   	
   }


    // change crosslinks from resourcepage instance to module id
    if ($result && $oldversion < 2008101500) {

        $tw=new transaction_wrapper();
        // check if the [prefix]_resourcepage_items_crosslink_fkey exists and drop if it does
        $sql = "SELECT COUNT(1) FROM INFORMATION_SCHEMA.referential_constraints WHERE constraint_name='".$CFG->prefix."resourcepage_items_crosslink_fkey'";
        if(get_field_sql($sql)) {
            $sql = "ALTER TABLE ".$CFG->prefix."resourcepage_items DROP CONSTRAINT ".$CFG->prefix."resourcepage_items_crosslink_fkey";
            $result = execute_sql($sql);
        }

        // update the crosslink references
        $sql = "UPDATE ".$CFG->prefix."resourcepage_items SET crosslink=(
                SELECT id FROM ".$CFG->prefix."course_modules cm
                WHERE cm.instance=crosslink
                and cm.module=(SELECT id FROM ".$CFG->prefix."modules WHERE name='resourcepage'))";
        $result = execute_sql($sql);

        if($result) {
            $tw->commit();
        }  	   	
    }

    // Rename resourcepage_items.level column to headinglevel as necessary
    if ($result && $oldversion < 2009011500) {

    /// Rename field level on table resourcepage_items to headinglevel
        $table = new XMLDBTable('resourcepage_items');
        $field = new XMLDBField('level');

    /// Only rename if level column exists
        if (field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_INTEGER, '5', null, null, null, null, null, null, 'basedonitemid');

        /// Launch rename field headinglevel
            $result = $result && rename_field($table, $field, 'headinglevel');
        }
    }

    if ($result && $oldversion < 2009012200) {
        $test=get_field('resourcepage_canned','html','canned','accessfiles');
        if(strpos($test,'%%FLAGICON%%')==false) {
            set_field('resourcepage_canned','html',addslashes('<img src="%%FLAGICON%%/inaccessible.gif" alt="X icon, read as \'not accessible to screen readers\'" /> Files marked with a red X are not accessible to those using screen reading software.'),
                'canned','accessfiles');
        }
    }
    
    // Rename resourcepage_items.level column to headinglevel as necessary
    if ($result && $oldversion < 2009011500) {

    /// Rename field level on table resourcepage_items to headinglevel
        $table = new XMLDBTable('resourcepage_items');
        $field = new XMLDBField('level');

    /// Only rename if level column exists
        if (field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_INTEGER, '5', null, null, null, null, null, null, 'basedonitemid');

        /// Launch rename field headinglevel
            $result = $result && rename_field($table, $field, 'headinglevel');
        }
    }

    // Make sure plugininfo field is 255 characters long
    if ($result && $oldversion < 2009051801) {
        execute_sql("ALTER TABLE {$CFG->prefix}resourcepage_containers ALTER COLUMN plugininfo TYPE varchar(255) USING substring(plugininfo,1,255)");
    }
    
    // Make sure title character is 1023 characters
    if ($result && $oldversion < 2009100600) {
        execute_sql("ALTER TABLE {$CFG->prefix}resourcepage_items ALTER COLUMN title TYPE varchar(1023) USING substring(title,1,1023)");
    }
   
// TELSTAR references
    if ($result && $oldversion < 2009102001) {
       
    /// Define field data to be added to resourcepage_items
        $table = new XMLDBTable('resourcepage_items');
        $field = new XMLDBField('data');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null, 'rights');

    /// Launch add field data
        $result = $result && add_field($table, $field);
        

    /// Define field refstyle to be added to resourcepage
        $table = new XMLDBTable('resourcepage');
        $field = new XMLDBField('refstyle');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', null, null, null, null, null, '0', 'autocreatetype');

    /// Launch add field refstyle
        $result = $result && add_field($table, $field);
        
        /// Define field exportrefs to be added to resourcepage
        $table = new XMLDBTable('resourcepage');
        $field = new XMLDBField('exportrefs');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, null, null, '0', 'refstyle');

    /// Launch add field exportrefs
        $result = $result && add_field($table, $field);
    
    /// Changing type of field title on table resourcepage_items to text
        $table = new XMLDBTable('resourcepage_items');
        $field = new XMLDBField('title');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null, 'showto');

    /// Launch change of type for field title
        $result = $result && change_field_type($table, $field);    

    /// Changing type of field weblink on table resourcepage_items to text
        $table = new XMLDBTable('resourcepage_items');
        $field = new XMLDBField('weblink');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null, 'forcehide');

    /// Launch change of type for field weblink
        $result = $result && change_field_type($table, $field);
    }
    
    //More TELSTAR
    if ($result && $oldversion < 2009102002) {

    /// Changing type of field weblink on table resourcepage_items to text
        $table = new XMLDBTable('resourcepage_items');
        $field = new XMLDBField('weblink');
        $field->setAttributes(XMLDB_TYPE_CHAR, '4000', XMLDB_UNSIGNED, null, null, null, null, null, 'forcehide');

    /// Launch change of type for field weblink
        $result = $result && change_field_type($table, $field);
    }
    
    return $result;
    
}




?>